import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Button,
  Table,
  Modal,
  Tooltip,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import SaveCabinetElem from './components/SaveCabinetElem';

const typeText = ['', '柜体', '货架', '地堆'];

interface CabinetProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  dataInfo: any;
  location: { query: any };
}

interface CabinetState {
  visible: boolean;
  pageIndex: number;
  pageSize: number;
  delVisible: boolean;
  delId: number | string;
  rowId:number;
}

@connect((state: any) => {
  const {
    partitionManagementCabinet: { dataInfo },
    loading,
  } = state;
  return {
    dataInfo,
    loading: loading.effects['partitionManagementCabinet/fetchLogisRegion'],
  };
})

class CabinetElem extends Component<CabinetProps, CabinetState> {
  columns = [
    { title: 'ID', dataIndex: 'id' },
    {
      title: '名称',
      dataIndex: 'name',
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    { title: '类型', dataIndex: 'type', render: (val: number) => typeText[val] },
    { title: '添加时间', dataIndex: 'createTime' },
    {
      title: '操作',
      width: 80,
      render: (val: any, record: any) => (
        <span
          className="operLink"
          onClick={() => this.changeDelModal(true, record)}
        >
          删除
        </span>
      ),
    },
  ];

  state: CabinetState = {
    visible: false,
    pageIndex: 1,
    pageSize: 20,
    delVisible: false,
    delId: '',
    rowId: 0,
  };

  componentDidMount() {
    const {
      location: { query: { id } },
    } = this.props;
    if (id) this.fetchDataInfo(id);
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const {
      location: { query: { id } },
    } = this.props;
    if (id && id !== prevProps.location.query.id) {
      this.fetchDataInfo(id);
    }
  }

  fetchDataInfo = (id: number) => {
    const { pageIndex, pageSize } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'partitionManagementCabinet/fetchLogisRegion',
      payload: { regionId: id, pageIndex, pageSize },
    });
  };

  changeVisible = (status: boolean) => {
    this.setState({ visible: status }, () => {
      if (status) {
        const params = {
          type: 0,
          pageIndex: 1,
          pageSize: 20,
        };
        this.fetchAction('saveList', params);
        this.fetchAction('common/fetchLogisList');
      }
    });
  };

  handleDeleteSure = () => {
    const { delId: id, pageIndex, pageSize } = this.state;
    const {
      location: {
        query: { id: regionId },
      },
    } = this.props;
    const params = {
      id,
      search: { regionId, pageIndex, pageSize },
    };
    this.fetchAction('delete', params);
    this.changeDelModal(false);
  };

  changeDelModal = (delVisible: boolean, params?: any) => {
    this.setState({
      delVisible,
      delId: params ? params.id : '',
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const {
      location: { query: { id: regionId } },
    } = this.props;
    this.setState({ pageIndex, pageSize }, () => {
      this.fetchAction('fetchLogisRegion', { regionId, pageIndex, pageSize });
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload = {}) => {
    if (typeName === 'saveCabs') {
      const {
        location: {
          query: { id: regionId },
        },
      } = this.props;

      this.setState({ pageIndex: 1, pageSize: 20 });
      payload = {
        search: { regionId, pageIndex: 1, pageSize: 20 },
        ...payload,
        regionId,
      };
    }

    const type = typeName.indexOf('common') >= 0
      ? typeName : `partitionManagementCabinet/${typeName}`;
    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  render() {
    const {
      visible, pageIndex, pageSize, delVisible,
    } = this.state;
    const { dataInfo, loading } = this.props;
    const dataSource = dataInfo.list;
    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="tableList marginT12">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={() => this.changeVisible(true)}
            >
              添加
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            loading={loading}
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            scroll={{ x: 700 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <SaveCabinetElem
          visible={visible}
          fetchAction={this.fetchAction.bind(this)}
          changeVisible={this.changeVisible.bind(this)}
        />

        <Modal
          title="删除柜体"
          visible={delVisible}
          okText="删除"
          onOk={this.handleDeleteSure}
          onCancel={() => this.changeDelModal(false)}
        >
          <p>确定删除当前柜体吗？</p>
        </Modal>
      </Fragment>
    );
  }
}

export default Form.create<CabinetProps>()(CabinetElem);
